import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import { Balloon } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import MemberTrigger from 'components/memberTrigger';
import utils from 'utils/index';
import { PROJECT_WRITE_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import UILessPluginForCode from 'components/UILessPluginForCode';
import Assignees from './assignees';
import docs from 'utils/docs';
import exceed from 'utils/apimap';
import './index.scss';
import track from 'utils/track';
import { getFeature } from 'utils/features';
import intl from '../../../../../../../../../locale';
import FeedbackCollection from './mrFeedback';
const { pathResource } = window.FORCE;
// mr 基本信息
const prefix = 'mr-basic-info';
export default class BasicInfo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      defaultReviewerList: [],
    };
  }

  componentDidMount() {
    const { source_branch, target_branch, state } = this.props.codeReviewDetail;
    // 已合并和已关闭MR不用调
    if (this.props.is_enable_reviewer_recommend && state !== 'closed' && state !== 'merged') {
      // 获取推荐评审人
      Promise.all([this.getLastCommit(source_branch), this.getLastCommit(target_branch)]).then(
        (results) => {
          const [result1, result2] = results;
          const sourceBranchSha = result1.id;
          const targetBranchSha = result2.id;
          this.getRecommendReviewers(
            pathResource.id,
            sourceBranchSha,
            targetBranchSha,
            (resultList) => {
              this.setState({
                defaultReviewerList: resultList,
              });
            },
          );
        },
      );
    }
  }

  // 获取推荐评审人
  getRecommendReviewers = (projectId, sourceBranchSha, targetBranchSha, callback) => {
    if (projectId === null) {
      callback([]);
      return;
    }

    const data = {};
    if (sourceBranchSha) {
      data.source_version = sourceBranchSha;
    }

    if (targetBranchSha) {
      data.target_version = targetBranchSha;
    }

    exceed
      .forceFetch({
        api: 'merge_request.reviewer_recommend.get',
        params: {
          projectId,
        },

        data,
      })
      .then((res) => {
        const list = res.list.sort((a, b) => {
          return b.score - a.score;
        });
        callback(list);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  getLastCommit(sha) {
    return new Promise((resolve) => {
      exceed
        .forceFetch({
          api: 'projects.files.last_commit',
          params: { projectId: pathResource.id },
          data: {
            sha,
            filepath: '/',
          },
        })
        .then((result) => {
          resolve(result);
        });
    });
  }

  onSelectMember = (value) => {
    const { codeReviewDetail } = this.props;
    const { assignees } = codeReviewDetail;
    const { defaultReviewerList } = this.state;
    const modifyData = {};
    modifyData.tb_user_ids = value.map((item) => item._userId || item.tb_user_id).join(',');
    this.props.modifyCr(modifyData);
    const original_reviewers = assignees ? assignees.map((item) => item.id) : [];
    const new_reviewers = value ? value.map((item) => item.id) : [];
    const recommend_reviewers = defaultReviewerList.filter((item) => {
      return (
        item.tag &&
        item.tag.children ===
          intl.get({
            id: 'code-assets.components.basicInfo.Recommended',
            defaultMessage: '推荐',
          }) &&
        new_reviewers.includes(item.id)
      );
    });

    const cur_recommend_reviewers = recommend_reviewers.map((item) => {
      return {
        user_id: item.id,
        score: item.score,
      };
    });
    track({
      action: 'mr_reviewer_chang',
      page: 'Repo-MR',
      type: '',
      mr_id: codeReviewDetail.id,
      original_reviewers: JSON.stringify(original_reviewers),
      new_reviewers: JSON.stringify(new_reviewers),
    });

    if (cur_recommend_reviewers && cur_recommend_reviewers.length) {
      const cur_assignees = value
        ? value.map((item) => {
            return {
              user_id: item.id,
            };
          })
        : [];
      track({
        action: 'reviewer_modify',
        page: 'Repo-MR',
        type: '',
        mr_id: codeReviewDetail.id,
        user_id: window.FORCE.user ? window.FORCE.user.id : '',
        code_user_id: window.FORCE.user ? window.FORCE.user.codeUserId : '',
        recommend_reviewers: JSON.stringify(cur_recommend_reviewers),
        assignees: JSON.stringify(cur_assignees),
      });
    }
  };

  render() {
    const { defaultReviewerList } = this.state;
    const { codeReviewDetail } = this.props;
    const { role } = pathResource;

    const { assignees } = codeReviewDetail;
    const time_doc =
      codeReviewDetail.attributes &&
      codeReviewDetail.attributes.length &&
      codeReviewDetail.attributes[0].attributeType === 'merge_request_time'
        ? JSON.parse(codeReviewDetail.attributes[0].attributeInfo).time_doc
        : '';
    let timeTxt = null;
    if (time_doc === 'unsupported') {
      timeTxt = (
        <div>
          {intl.get({ id: 'code-assets.components.basicInfo.NA', defaultMessage: '暂无' })}

          <Balloon
            closable={false}
            trigger={
              <ButtonIcon name="question-line" style={{ marginLeft: 4, display: 'inline-block' }} />
            }
            align="t"
          >
            {intl.get({
              id: 'code-assets.components.basicInfo.CurrentlyTheFileTypeCannot',
              defaultMessage: '文件类型暂不支持预估，查看',
            })}

            <a
              href={docs('estimatedReviewTime')}
              target="_blank"
              style={{ color: '#488ee2' }}
              rel="noreferrer"
            >
              {intl.get({
                id: 'code-assets.components.basicInfo.ServiceDescription',
                defaultMessage: '服务说明',
              })}
            </a>
          </Balloon>
        </div>
      );
    } else if (time_doc.startsWith('>')) {
      const time = time_doc.slice(1);
      timeTxt = intl.get(
        {
          id: 'code-assets.components.basicInfo.MoreThanTimeMinutes',
          defaultMessage: '大于 {time} 分钟',
        },
        { time },
      );
    } else {
      timeTxt = intl.get(
        {
          id: 'code-assets.components.basicInfo.AboutTimedocMinutes',
          defaultMessage: '约 {timeDoc} 分钟',
        },
        { timeDoc: time_doc },
      );
    }
    return (
      <>
        <div className={`${prefix}`}>
          <div className={`${prefix}-title`}>
            {intl.get({
              id: 'code-assets.components.basicInfo.BasicInformation',
              defaultMessage: '基本信息',
            })}
          </div>
          <div className={`${prefix}-time`}>
            {time_doc ? (
              <div className={`${prefix}-time-left`}>
                <div className="title">
                  <span>
                    {intl.get({
                      id: 'code-assets.components.basicInfo.EstimatedTimeConsumption',
                      defaultMessage: '耗时预估',
                    })}
                  </span>
                </div>
                <div className="content">{timeTxt}</div>
              </div>
            ) : null}

            <div className={`${prefix}-time-right`}>
              <div className="title">
                {intl.get({
                  id: 'code-assets.components.basicInfo.Created',
                  defaultMessage: '创建时间',
                })}
              </div>
              <div className="content">{utils.getBeautyTime(codeReviewDetail.created_at)}</div>
            </div>
          </div>

          <div className={`${prefix}-assignees`}>
            <div className={`${prefix}-assignees-title`}>
              <div>
                {intl.get({
                  id: 'code-assets.components.basicInfo.Reviewer',
                  defaultMessage: '评审人',
                })}
              </div>
              <div className={`${prefix}-assignees-title-right`}>
                {access(PROJECT_WRITE_ROLES, role) ? (
                  <MemberTrigger
                    useRecommendMember={defaultReviewerList && defaultReviewerList.length}
                    recommendList={defaultReviewerList}
                    useExtraMember="project"
                    useProjectMember
                    onChange={this.onSelectMember}
                    value={assignees}
                    align="tr br"
                    needAvatar
                    multiple
                    trigger={
                      <div>
                        <ButtonIcon name="add-line" />
                      </div>
                    }
                    pathResourceId={Number(window.FORCE.pathResource.id)}
                  />
                ) : (
                  <Balloon.Tooltip
                    trigger={<ButtonIcon name="add-line" disabled />}
                    align="t"
                    triggerType="hover"
                  >
                    {intl.get({
                      id: 'code-assets.components.basicInfo.YouAreNotAuthorizedTo',
                      defaultMessage: '无权限进行编辑操作，请联系管理员申请对应的权限',
                    })}
                  </Balloon.Tooltip>
                )}
              </div>
            </div>

            <MemberTrigger
              useRecommendMember={defaultReviewerList && defaultReviewerList.length}
              recommendList={defaultReviewerList}
              useExtraMember="project"
              useProjectMember
              onChange={this.onSelectMember}
              value={assignees}
              align="tr br"
              needAvatar
              multiple
              trigger={
                <div className={`${prefix}-assignees-content`}>
                  <Assignees value={assignees} needAvatar />
                </div>
              }
              pathResourceId={Number(window.FORCE.pathResource.id)}
            />
          </div>
          {/* unsupport_workitem_message is_support_workitem 集团codeup不支持关联变更也不涉及更改，暂未使用到 */}

          <UILessPluginForCode
            identifier="plugin_for_code_mr"
            container={{
              target: 'merge_request',
              id: codeReviewDetail.id,
            }}
          />
        </div>
        {getFeature('project.mr.feedback.collect') && <FeedbackCollection />}
      </>
    );
  }
}
